package com.example.casper.jnuexperiment2025;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.casper.jnuexperiment2025.dataop.Book;
import com.example.casper.jnuexperiment2025.dataop.DataBank;

import java.util.ArrayList;
import java.util.List;

public class Hello03513Activity extends AppCompatActivity {

    public List<Book> books;
    public RecyclerViewBookAdpater recyclerViewBookAdpater;
    ActivityResultLauncher<Intent> addBookLauncher;
    ActivityResultLauncher<Intent> updateBookLauncher;
    private DataBank dataBank;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello03513);

        
        dataBank = new DataBank();

        
        books = dataBank.loadBooks(this);

        
        if (books.isEmpty()) {
            books = getDefaultBooks();
            
            dataBank.saveBooks(this, books);
        }

        RecyclerView mainRecyclerView = findViewById(R.id.recycler_view_my_books);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerViewBookAdpater = new RecyclerViewBookAdpater(books);
        mainRecyclerView.setAdapter(recyclerViewBookAdpater);

        
        addBookLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            String title = data.getStringExtra("title");
                            int bookCover = R.drawable.book_no_name;
                            int position = data.getIntExtra("book_position", -1);

                            if (position != -1) {
                                int insertPosition = position + 1;
                                if (insertPosition > books.size()) {
                                    insertPosition = books.size();
                                }
                                Book book = new Book(title, bookCover);
                                books.add(insertPosition, book);
                                recyclerViewBookAdpater.notifyItemInserted(insertPosition);

                                
                                dataBank.saveBooks(Hello03513Activity.this, books);
                            }
                        }
                    }
                }
        );

        
        updateBookLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            String title = data.getStringExtra("title");
                            int position = data.getIntExtra("book_position", -1);

                            if (position != -1 && position < books.size()) {
                                Book book = books.get(position);
                                book.setTitle(title);
                                recyclerViewBookAdpater.notifyItemChanged(position);

                                
                                dataBank.saveBooks(Hello03513Activity.this, books);
                            }
                        }
                    }
                }
        );

        registerForContextMenu(mainRecyclerView);
    }
    private List<Book> getDefaultBooks() {
        List<Book> defaultBooks = new ArrayList<>();
        defaultBooks.add(new Book("Java编程", R.drawable.book_no_name));
        defaultBooks.add(new Book("Android开发", R.drawable.book_no_name));
        defaultBooks.add(new Book("算法导论", R.drawable.book_no_name));
        return defaultBooks;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int position = item.getOrder();

        if (position < 0 || position > books.size()) {
            return super.onContextItemSelected(item);
        }

        switch (item.getItemId()) {
            case 0: 
                Intent intent = new Intent(Hello03513Activity.this, BookDetailsActivity.class);
                intent.putExtra("book_position", position);
                addBookLauncher.launch(intent);
                break;
            case 1: 
                if (position < books.size()) {
                    Intent intentUpdate = new Intent(Hello03513Activity.this, BookDetailsActivity.class);
                    Book book = books.get(position);
                    intentUpdate.putExtra("title", book.getTitle());
                    intentUpdate.putExtra("book_position", position);
                    updateBookLauncher.launch(intentUpdate);
                }
                break;
            case 2: 
                showDeleteConfirmationDialog(position);
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }

    private void showDeleteConfirmationDialog(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(Hello03513Activity.this);
        builder.setTitle("删除");
        builder.setMessage("确定要删除吗？");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (position >= 0 && position < books.size()) {
                    books.remove(position);
                    recyclerViewBookAdpater.notifyItemRemoved(position);

                    
                    dataBank.saveBooks(Hello03513Activity.this, books);
                }
            }
        });
        builder.setNegativeButton("否", null);
        builder.create().show();
    }

    public class RecyclerViewBookAdpater extends RecyclerView.Adapter<RecyclerViewBookAdpater.ViewHolder> {
        private List<Book> books;

        public RecyclerViewBookAdpater(List<Book> books) {
            this.books = books;
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            public final TextView textViewTitle;
            public final ImageView imageViewCover;

            public ViewHolder(View bookView) {
                super(bookView);
                textViewTitle = bookView.findViewById(R.id.text_view_book_name);
                imageViewCover = bookView.findViewById(R.id.image_view_book_cover);
                bookView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("操作菜单");
                menu.add(0, 0, getAdapterPosition(), "添加");
                menu.add(0, 1, getAdapterPosition(), "更新");
                menu.add(0, 2, getAdapterPosition(), "删除");
            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_item_row, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Book book = books.get(position);
            holder.textViewTitle.setText(book.getTitle());
            holder.imageViewCover.setImageResource(book.getBookCover());
        }

        @Override
        public int getItemCount() {
            return books.size();
        }
    }
}